<template>
  <div class="profile-container">
    <div class="profile-card">
      <div class="avatar-section">
        <div class="avatar-wrapper" @click="triggerFileInput">
          <img :src="userInfo.headPicture || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'" alt="用户头像" class="avatar" />
          <div class="avatar-overlay">
            <i class="el-icon-camera"></i>
            <span>点击更换头像</span>
          </div>
        </div>
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          accept="image/*"
          @change="handleAvatarChange"
        />
      </div>
      <div class="info-section">
        <div class="info-item">
          <span class="label">用户名：</span>
          <span class="value">{{ userInfo.username }}</span>
        </div>
        <div class="info-item">
          <span class="label">姓名：</span>
          <template v-if="!isEditing.realname">
            <span class="value">{{ userInfo.realname }}</span>
            <el-button type="text" @click="startEdit('realname')">
              <i class="el-icon-edit"></i>
            </el-button>
          </template>
          <template v-else>
            <el-input
              v-model="editForm.realname"
              size="small"
              @blur="saveEdit('realname')"
            ></el-input>
          </template>
        </div>
        <div class="info-item">
          <span class="label">身份证号：</span>
          <template v-if="!isEditing.idCard">
            <span class="value">{{ userInfo.idCard }}</span>
            <el-button type="text" @click="startEdit('idCard')">
              <i class="el-icon-edit"></i>
            </el-button>
          </template>
          <template v-else>
            <el-input
              v-model="editForm.idCard"
              size="small"
              @blur="saveEdit('idCard')"
            ></el-input>
          </template>
        </div>
        <div class="info-item">
          <span class="label">手机号：</span>
          <template v-if="!isEditing.phone">
            <span class="value">{{ userInfo.phone }}</span>
            <el-button type="text" @click="startEdit('phone')">
              <i class="el-icon-edit"></i>
            </el-button>
          </template>
          <template v-else>
            <el-input
              v-model="editForm.phone"
              size="small"
              @blur="saveEdit('phone')"
            ></el-input>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  name: 'Profile',
  data() {
    return {
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      isEditing: {
        realname: false,
        idCard: false,
        phone: false
      },
      editForm: {
        realname: '',
        idCard: '',
        phone: ''
      }
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.userInfo
    })
  },
  methods: {
    ...mapActions(['updateUserInfo']),
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    handleAvatarChange(e) {
      const file = e.target.files[0]
      console.log('原始文件对象:', file);
      
      if (!file) return

      // 验证文件类型
      const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
      if (!allowedTypes.includes(file.type)) {
        this.$message.error('只支持 JPG、PNG、GIF 格式的图片')
        return
      }

      // 验证文件大小（限制为 2MB）
      const maxSize = 1024 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('图片大小不能超过 1GB')
        return
      }

      // 创建 FormData 对象
      const formData = new FormData()
      formData.append('file', file)
      
      // 添加调试信息
      console.log('FormData 对象:', formData);
      console.log('FormData 中的文件:', formData.get('file'));

      // 显示上传中提示
      const loading = this.$loading({
        lock: true,
        text: '头像上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      console.log('FormData 中的文件（发起请求前）:', formData.get('file'));
      // 发送请求到后端
      this.$uploadFile('/upLoadHeadPicture', formData.get('file'),onProgress => {
        loading.text = `上传中 ${onProgress}%`
      },).then(res => {
        if (res.code === 200) {
          const updatedUserInfo = { ...this.userInfo, headPicture: res.data }
          this.updateUserInfo(updatedUserInfo)
          this.$message.success('头像更新成功')
        } else {
          this.$message.error(response.msg || '上传失败')
        }
      }).catch(error => {
        console.error('上传头像失败:', error)
        this.$message.error('上传失败，请稍后重试')
      }).finally(() => {
        loading.close()
        // 清空文件输入框，允许重复上传相同文件
        this.$refs.fileInput.value = ''
      })
    },
    startEdit(field) {
      this.isEditing[field] = true
      this.editForm[field] = this.userInfo[field]
    },
    saveEdit(field) {
      if (this.validateField(field)) {
        const updatedUserInfo = { ...this.userInfo, [field]: this.editForm[field] }
        this.updateUserInfo(updatedUserInfo)
        this.isEditing[field] = false
        this.$message.success('保存成功')
      }
    },
    validateField(field) {
      const value = this.editForm[field]
      switch (field) {
        case 'phone':
          if (!/^1[3-9]\d{9}$/.test(value)) {
            this.$message.error('请输入正确的手机号码')
            return false
          }
          break
        case 'idCard':
          if (!/^\d{17}[\dXx]$/.test(value)) {
            this.$message.error('请输入正确的身份证号码')
            return false
          }
          break
        case 'realname':
          if (!value || value.length < 2) {
            this.$message.error('姓名不能少于2个字符')
            return false
          }
          break
      }
      return true
    }
  }
}
</script>

<style scoped>
.profile-container {
  margin: 0;
  padding: 0;
  display: block;
  min-height: 0vh;
  background: linear-gradient(135deg, #f0f2f5 0%, #e6e9f0 100%);
}

.profile-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 100%;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  overflow: hidden;
}

.profile-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
}

.profile-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.15);
}

.avatar-section {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.avatar-wrapper:hover .avatar {
  transform: scale(1.04);
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
  transition: all 0.3s ease;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item:hover {
  background-color: #f9f9f9;
  padding-left: 6px;
}

.label {
  width: 80px;
  color: #666;
  font-weight: 500;
  font-size: 14px;
}

.value {
  color: #333;
  flex: 1;
  font-size: 14px;
}

.el-button--text {
  padding: 0 8px;
  color: #409EFF;
}

.el-input {
  width: 160px;
}
</style>
